import { defineStore } from 'pinia'
import { asyncPageRouterMap, constantRouterMap } from '@/router'
import { generateRoutesFn1, generateRoutesFn2, flatMultiLevelRoutes } from '@/utils/routerHelper'
import { store } from '../index'
import { cloneDeep } from 'lodash-es'
import { useCache } from '@/hooks/web/useCache'
import { RouteRecordRaw } from 'vue-router'
import getRouterList from '@/views/Login/components/roleMenu'
import { listToTree } from '@/utils/tree'
import api from '@/api'

export interface PermissionState {
    routers: AppRouteRecordRaw[]
    addRouters: AppRouteRecordRaw[]
    isAddRouters: boolean
    menuTabRouters: AppRouteRecordRaw[]
}
export const usePermissionStore = defineStore({
    id: 'permission',
    state: (): PermissionState => ({
        routers: [],
        addRouters: [],
        isAddRouters: false,
        menuTabRouters: []
    }),
    persist: {
        enabled: true
    },
    getters: {
        getRouters(): AppRouteRecordRaw[] {
            return this.routers
        },
        getAddRouters(): AppRouteRecordRaw[] {
            return flatMultiLevelRoutes(cloneDeep(this.addRouters))
        },
        getIsAddRouters(): boolean {
            return this.isAddRouters
        },
        getMenuTabRouters(): AppRouteRecordRaw[] {
            return this.menuTabRouters
        }
    },
    actions: {
        generateRoutes(
            type: 'backend' | 'frontend' | 'none',
            routers?: AppCustomRouteRecordRaw[] | string[]
        ): Promise<unknown> {
            return new Promise<void>((resolve) => {
                //const routerApi:any=asyncPageRouterMap;
                const routerApi: any = constantRouterMap
                let routerMap: AppRouteRecordRaw[] = []
                if (type === 'backend') {
                    // 后端过滤菜单
                    routerMap = generateRoutesFn2(routers as AppCustomRouteRecordRaw[])
                    routerMap = cloneDeep(routerApi).concat(routerMap)
                } else if (type === 'frontend') {
                    // 前端过滤菜单
                    routerMap = generateRoutesFn1(cloneDeep(routerApi), routers as string[])
                } else {
                    // 直接读取静态路由表
                    routerMap = cloneDeep(routerApi)
                }
                // 动态路由，404一定要放到最后面
                this.routers = cloneDeep(constantRouterMap).concat(routerMap)
                this.addRouters = routerMap.concat([
                    {
                        path: '/:path(.*)*',
                        redirect: '/404',
                        name: '404Page',
                        meta: {
                            hidden: true,
                            breadcrumb: false
                        }
                    }
                ])
                // 渲染菜单的所有路由
                resolve()
            })
        },
        async getRouterResources(name = 'xg12345') {
            // @ts-ignore
            const { getPermission } = api
            const { addRoute } = window.$router
            //const appealStore = useAppealStore();
            const { wsCache } = useCache()
            let routers: any = []
            //固定菜单
            // const res = await appealStore.getOrgData();
            // routers = getRouterList(res.data)
            //动态菜单
            try {
                const routerRes = await getPermission({ module: name })
                routers = routerRes.data
                routers.map((m) => {
                    const att = new Object()
                    if (m.attrs) {
                        const attrs = m.attrs.split(',')
                        attrs.map((n) => {
                            if (n.includes('=')) {
                                att[n.split('=')[0].trim()] = n.split('=')[1].trim()
                            } else if (n.includes(':')) {
                                att[n.split(':')[0].trim()] = n.split(':')[1].trim()
                            }
                        })
                    }
                    m.meta = {
                        title: m.title,
                        icon: m.icon ? m.icon : 'carbon:skill-level-advanced',
                        ...att
                    }
                })
            } catch (err) {
                console.log(err)
            }
            routers = listToTree(routers, { id: 'id', pid: 'parentId' })

            wsCache.set('roleRouters', routers)

            await this.generateRoutes('backend', routers as any).catch(() => {})
            this.getAddRouters.forEach((route) => {
                addRoute(route as RouteRecordRaw) //动态添加可访问路由表
            })
            this.setIsAddRouters(true)
        },
        setIsAddRouters(state: boolean): void {
            this.isAddRouters = state
        },
        setMenuTabRouters(routers: AppRouteRecordRaw[]): void {
            this.menuTabRouters = routers
        }
    }
})

export const usePermissionStoreWithOut = () => {
    return usePermissionStore(store)
}
